package com.japancompany.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.japancompany.entity.Category;
import com.japancompany.mapper.CategoryMapper;
import com.japancompany.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getCategoryList() {
        return list(new QueryWrapper<Category>()
                .eq("deleted", 0)
                .eq("status", 1)
                .orderByAsc("sort")
                .orderByDesc("create_time"));
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> allCategories = getCategoryList();
        
        Map<Integer, List<Category>> categoryMap = allCategories.stream()
                .filter(category -> category.getParentId() != null && category.getParentId() != 0)
                .collect(Collectors.groupingBy(Category::getParentId));
        
        List<Category> rootCategories = allCategories.stream()
                .filter(category -> category.getParentId() == null || category.getParentId() == 0)
                .collect(Collectors.toList());
        
        for (Category rootCategory : rootCategories) {
            buildCategoryTree(rootCategory, categoryMap);
        }
        
        return rootCategories;
    }

    private void buildCategoryTree(Category category, Map<Integer, List<Category>> categoryMap) {
        List<Category> children = categoryMap.get(category.getId().intValue());
        if (children != null && !children.isEmpty()) {
            category.setChildren(children);
            for (Category child : children) {
                buildCategoryTree(child, categoryMap);
            }
        } else {
            category.setChildren(new ArrayList<>());
        }
    }

    @Override
    public boolean createCategory(Category category) {
        if (getByCategoryCode(category.getCategoryCode()) != null) {
            throw new RuntimeException("分类编码已存在");
        }
        return save(category);
    }

    @Override
    public boolean updateCategory(Category category) {
        Category existingCategory = getById(category.getId());
        if (existingCategory == null) {
            throw new RuntimeException("分类不存在");
        }
        
        if (!existingCategory.getCategoryCode().equals(category.getCategoryCode())) {
            if (getByCategoryCode(category.getCategoryCode()) != null) {
                throw new RuntimeException("分类编码已存在");
            }
        }
        
        return updateById(category);
    }

    @Override
    public boolean deleteCategory(Long id) {
        Category category = getById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        
        long childCount = count(new QueryWrapper<Category>()
                .eq("parent_id", id)
                .eq("deleted", 0));
        
        if (childCount > 0) {
            throw new RuntimeException("该分类下还有子分类，不能删除");
        }
        
        return removeById(id);
    }

    private Category getByCategoryCode(String categoryCode) {
        return getOne(new QueryWrapper<Category>()
                .eq("category_code", categoryCode)
                .eq("deleted", 0));
    }
}